<template>
  <el-dialog
    title="批量导入教学任务"
    :model-value="visible"
    width="50%"
    :close-on-click-modal="false"
    @update:model-value="updateVisible"
    @close="handleClose"
  >
    <div class="import-content">
      <el-alert
        title="导入说明"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>1. 请先下载模板文件，按照模板格式填写教学任务信息</p>
          <p>2. <span style="color: red; font-weight: bold;">必填字段</span>：课程编码、学期名称、教师用户名</p>
          <p>3. <span style="color: green; font-weight: bold;">可选字段</span>：任务名称、班级名称、备注</p>
          <p>4. 课程编码和学期名称必须在系统中存在</p>
          <p>5. 多个教师用逗号分隔，用*标记主讲教师（如：teacher001*,teacher002）</p>
          <p>6. 多个班级用逗号分隔（如：班级1,班级2）</p>
          <p>7. 如有数据错误，将不会保存任何数据，请修正后重新导入</p>
        </template>
      </el-alert>

      <el-upload
        ref="uploadRef"
        class="upload-area"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls"
        :limit="1"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 Excel 文件，且文件大小不超过 10MB
          </div>
        </template>
      </el-upload>

      <div v-if="importResult" class="import-result">
        <el-alert
          :title="importResult.message"
          :type="importResult.success ? 'success' : 'error'"
          :closable="false"
          show-icon
        >
          <template #default>
            <p v-if="importResult.success">
              成功导入 {{ importResult.data?.successCount || 0 }} 条教学任务记录
            </p>
            <p v-if="importResult.data?.failureCount > 0">
              失败 {{ importResult.data.failureCount }} 条记录
            </p>
            <div v-if="importResult.data?.errors?.length > 0" class="error-details">
              <p><strong>错误详情：</strong></p>
              <div class="error-content">
                <div v-for="(error, index) in importResult.data.errors" :key="index" class="error-item">
                  <pre>{{ error }}</pre>
                </div>
              </div>
            </div>
          </template>
        </el-alert>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="cancelImport">取消</el-button>
      <el-button type="success" @click="handleDownloadTemplate">
        <el-icon><Download /></el-icon> 下载模板
      </el-button>
      <el-button type="primary" @click="handleSubmit" :loading="importing" :disabled="!selectedFile">
        导入
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, watch } from 'vue'
import { Download, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'TeachingMissionImportDialog',
  components: {
    Download,
    UploadFilled
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    importing: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'submit', 'download-template'],
  setup(props, { emit }) {
    const visible = ref(false)
    const fileList = ref([])
    const selectedFile = ref(null)
    const importResult = ref(null)
    const uploadRef = ref(null)
    
    // 监听modelValue变化
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val) {
        // 重置状态
        fileList.value = []
        selectedFile.value = null
        importResult.value = null
      }
    }, { immediate: true })
    
    // 监听visible变化
    watch(visible, (val) => {
      emit('update:modelValue', val)
    })
    
    const updateVisible = (value) => {
      emit('update:modelValue', value)
    }
    
    const handleClose = () => {
      emit('update:modelValue', false)
    }
    
    const cancelImport = () => {
      emit('update:modelValue', false)
    }
    
    const handleFileChange = (file) => {
      selectedFile.value = file.raw
      fileList.value = [file]
      // 清除之前的导入结果
      importResult.value = null
    }
    
    const handleDownloadTemplate = () => {
      emit('download-template')
    }
    
    const handleSubmit = () => {
      if (!selectedFile.value) {
        ElMessage.warning('请选择要导入的文件')
        return
      }
      
      // 清除之前的结果
      importResult.value = null
      emit('submit', selectedFile.value)
    }
    
    // 设置导入结果（由父组件调用）
    const setImportResult = (result) => {
      importResult.value = result
    }
    
    return {
      visible,
      fileList,
      selectedFile,
      importResult,
      uploadRef,
      updateVisible,
      handleClose,
      cancelImport,
      handleFileChange,
      handleDownloadTemplate,
      handleSubmit,
      setImportResult
    }
  }
}
</script>

<style scoped>
.import-content {
  margin-bottom: 20px;
}

.upload-area {
  margin: 20px 0;
}

.import-result {
  margin-top: 20px;
}

.error-details {
  margin-top: 10px;
}

.error-content {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #fafafa;
}

.error-item {
  padding: 8px 12px;
  border-bottom: 1px solid #e0e0e0;
}

.error-item:last-child {
  border-bottom: none;
}

.error-item pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 12px;
  color: #f56c6c;
  background: none;
}
</style>
